package com.lgl.service;

import com.lgl.handler.UserServiceHandler;
import com.lgl.pojo.RpcRequest;
import com.lgl.serializer.JSONSerializerImpl;
import com.lgl.tools.RpcDecoder;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import org.springframework.stereotype.Service;

/**
 * @Auther: Brook
 * @Date: 2020/10/18 09:03
 * @Description:
 */
@Service
public class UserServiceImpl implements IUserService {

    //将来客户端要调用的远程方法
    public String sayHello(String msg) {
        System.out.println("服务器响应到数据， 接收参数为：" + msg);
        return "返回数据：" + msg;
    }


    //创建一个方法启动服务
    public static void startServer(String ip, int port) throws InterruptedException {
        //1. 创建俩个线程池对象
        NioEventLoopGroup boosGroup = new NioEventLoopGroup();
        NioEventLoopGroup workGroup = new NioEventLoopGroup();

        //2.创建服务端的启动引导对象
        ServerBootstrap serverBootstrap = new ServerBootstrap();

        //3.配置启动引导对象
        serverBootstrap.group(boosGroup, workGroup)
                //设置通道为NIO
                .channel(NioServerSocketChannel.class)
                //创建监听
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        //获取管道对象
                        ChannelPipeline pipeline = nioSocketChannel.pipeline();
                        pipeline.addLast(new StringEncoder());
                        pipeline.addLast(new RpcDecoder(RpcRequest.class, new JSONSerializerImpl()));
                        //添加自定义的ChannelHandler到通道中
                        pipeline.addLast(new UserServiceHandler());
                    }
                });

        //4.绑定接口
        serverBootstrap.bind(port).sync();
        System.out.println("服务端启动, 端口号为: " + port);
    }
}
